package com.only4play.pcc.rest;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.concurrent.Callable;

/**
 * @author liyuncong
 * @version 1.0
 * @file GenericResponse
 * @brief GenericResponse
 * @details GenericResponse
 * @date 2024-06-24
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-06-24               liyuncong          Created
 */

@NoArgsConstructor
@Getter
@Setter
public class GenericResponse<T> extends AbstractResponse {

    private T payload;

    public GenericResponse(T payload) {
        this.payload = payload;
    }

    public GenericResponse(Integer errorCode, String errorMsg, T payload) {
        super(errorCode, errorMsg);
        this.payload = payload;
    }

    public static <T> GenericResponse<T> success() {
        return of(0, "", null);
    }

    public static <T> GenericResponse<T> success(T payload) {
        return of(0, "", payload);
    }

    public static <T> GenericResponse<T> failure() {
        return of(-1, "", null);
    }

    public static <T> GenericResponse<T> failure(String message) {
        return of(-1, message, null);
    }

    public static <T> GenericResponse<T> failure(String message, T payload) {
        return of(-1, message, payload);
    }

    public static <T> GenericResponse<T> of(int errorCode, String errorMsg, T payload) {
        return new GenericResponse<>(errorCode, errorMsg, payload);
    }

    public static <T> GenericResponse<T> doTryCatch(Callable<GenericResponse<T>> callable) {
        try {
            return callable.call();
        } catch (Exception exception) {
            return failure("Some exception happened.");
        }
    }
}

